package com.springcloudali.ms;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <h1>8位技术专家全程教学实战，全面覆盖Java进阶知识体系。<br/><br/><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">极客训练营地址：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/SpringCloudAlibabaTutorial">极客案例代码地址：https://gitee.com/ylimhhmily/SpringCloudAlibabaTutorial</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101</a></h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2023-05-12
 */
@Component
public class LoggerGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        exchange.getAttributes().put("START_TIME", System.currentTimeMillis());
        System.out.println("Start: " + exchange.getRequest().getURI());

        return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
            @Override
            public void run() {
                // 处理请求之后，这里也可以干点事情
                Long startTime = exchange.getAttribute("START_TIME");
                if(startTime != null){
                    long endTime = System.currentTimeMillis();
                    long cost = endTime - startTime;

                    System.out.println("End: " + exchange.getRequest().getURI()
                            + " 耗时为：" + cost + " 毫秒。");
                }
            }
        }));
    }
}
